package lore.miniwechat.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

// 启用web安全配置
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    AuthenticationSuccessHandler successHandler;

    @Autowired
    AuthenticationFailureHandler failureHandler;

    // 配置安全访问的一些规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                    // 登录配置
                    .formLogin()
                    .loginProcessingUrl("/login")// 指定登录请求的路径
                    .permitAll()   // 允许访问登录请求的url
                    .successHandler(successHandler) // 登录成功的处理
                    .failureHandler(failureHandler) // 登录失败的处理
                .and()
                    // 认证配置（哪些路径需要认证）
                    .authorizeRequests()
                    .antMatchers("/user/register").permitAll()   // 注册的不能拦截
                    .anyRequest()
                    .authenticated()
                .and()
                    // 认证出错的处理
                    // 未登录的时候，会调用认证出错的处理器
                .exceptionHandling()
                // 指定一个认证出错的处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
                    .csrf().disable();        // 关闭csrf()
        // super.configure(http);
    }

    // 让spring创建一个密码加密器, 采用bcrypt算法加密
    // 在进行密码校验的时候，spring security会自动查找这个密码加密器，对用户提交的密码加密
    @Bean
    public PasswordEncoder createPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
